package com.itheima.springbootmybatis.controller;


import ch.qos.logback.core.util.FileUtil;
import com.itheima.springbootmybatis.domain.User;
import com.itheima.springbootmybatis.service.UserService;
import com.itheima.springbootmybatis.socket.WebSocket;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.jeecgframework.poi.excel.entity.ImportParams;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService ;

    @Autowired
    private WebSocket webSocket ;

    @PostMapping("/add")
    public Boolean add(@RequestBody User user){
        userService.save(user);

        webSocket.oneMessage("添加成功",user.getId());
        return true ;
    }

    /**
     * 导入excel数据
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/excel")
    public Boolean excel(HttpServletRequest request, HttpServletResponse response){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setSheetNum(1);
            params.setNeedSave(true);
            try {
                List<User> listSysUsers = ExcelImportUtil.importExcel(file.getInputStream(), User.class, params);
                for (User UserExcel : listSysUsers) {
                    if (UserExcel.getPassword() == null) {
                        // 密码默认为“123456”
                        UserExcel.setPassword("123456");
                    }
                    userService.save(UserExcel);
                }
              //  return Result.ok("文件导入成功！数据行数：" + listSysUsers.size());
                return true ;
            } catch (Exception e) {
            //    log.error(e.getMessage(),e);
              //  return Result.error("抱歉! 您导入的数据中用户名已经存在.");
                return false ;
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                   // log.error(e.getMessage(), e);
                }
            }
        }
     ///   return Result.error("文件导入失败！");
          return true ;
    }


    /**
     * 导出excel模板
     *
     * @param request
     * @param
     */
    @PostMapping(value = "/queryExportUser")
    public void exportTemplateXls(HttpServletRequest request, HttpServletResponse response){

        OutputStream outputStream = null ;
        try {
            outputStream = response.getOutputStream();

            Workbook workbook = userService.queryUser();
            // FileUtil.setRes
            response.reset();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
